<?php
    include_once("../../includes/config.inc.php");
    check_login();
    $suserSession=get_suser();
    $customer_id=$suserSession['id'];
    $model=D('wx_send');
    $id=(int)$_POST['id'];

    if($_REQUEST['a']=='get_group'){
        //获取用户分组
        $configModel=new Model_CustomerConfig();
        $groupMsg=$configModel->getGroups($customer_id);
        echo json_encode($groupMsg);die;
    }

    if($_REQUEST['a']=='sendMulti'){
        //门店群发
        if($suserSession['type'] == 3){
            //获取token
            $configModel=new Model_CustomerConfig();
            $token=$configModel->getToken($customer_id);
            if (!$token) die(json_encode('无法获取token'));
            
            /****************群发还是预览****************/
            $is_preview=1;
            if($is_preview==1){
                $firstStr='"touser":"o7-rgsnLrVXUvSGCa7TwAD1oi_28"';//第一个字串
                $mass_api_url='https://api.weixin.qq.com/cgi-bin/message/mass/preview?access_token='.$token;//接口地址
            }else{
                if($_POST['groupid'] == -1){
                    $firstStr='"filter":{"is_to_all":true,"group_id":""}';
                }else{
                    $firstStr='"filter":{"is_to_all":false,"group_id":"'.$_POST['groupid'].'"}';
                }
                $mass_api_url='https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token='.$token;
            }
            
            //更新每个图文的封面图片media_id
            $detailArr=$model->where("id='{$id}' or pid='{$id}'")->dataArr();
            if($detailArr){
                foreach($detailArr as $k=>$v){
                    $detailUpdata=array();
                    $detailUpdata['media_id']=upImage($v['info_pic'],$token);
                    $model->updateById($v['id'],$detailUpdata);
                }
            }
            $detailArr=$model->where("id='{$id}' or pid='{$id}'")->order('order_num asc,id asc')->dataArr();
            
            //获取多图文的media_id
            $siglePageUrl='http://'.$_SERVER['HTTP_HOST'] .'/'.DIR_NAME. "/mobile/send.php?id=";
            $jsonStr = '{"articles":[';
            foreach ($detailArr as $val){
                if(!$val['info_url']) $val['info_url']=$siglePageUrl.$val['id'];//无外链的访问定制页面
                if(strstr($val['msg_content'],"='") || strstr($val['msg_content'],'="')){//引号未转义
                    $val['msg_content']=addslashes($val['msg_content']);
                }
                
                $jsonStr .= '{
                    "thumb_media_id":"'.$val['media_id'].'",
                     "title":"'.$val['info_title'].'",
                     "content_source_url":"'.$val['info_url'].'",
                     "content":"'.$val['msg_content'].'",
                     "show_cover_pic":"0"
                },';
            }
            $jsonStr = rtrim($jsonStr, ',') . ']}';
            $multiUpApi = "https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=".$token;
            $multiMediaMsg = http_request_curl($multiUpApi,$jsonStr);

            //推送多图文
            $jsonStr = '{
               '.$firstStr.',
               "mpnews":{"media_id":"'.$multiMediaMsg['media_id'].'"},
               "msgtype":"mpnews"
            }';
            //file_put_contents('cc.txt',$mass_api_url.'--'.$jsonStr,FILE_APPEND);$returnArray['errcode']=0;
            $returnArray = http_request_curl($mass_api_url,$jsonStr);

            if ($returnArray['errcode'] == 0){
                $model->updateById($id,array('is_send'=>1,'send_time'=>time()));
                die(json_encode('suc'));
            }else{
                die(json_encode($returnArray['errmsg']));
            }
        }
    }
    
    //上传图片素材取得meida_id
    function upImage($pic,$token) {
        $upFileUrl = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=".$token."&type=image";
        $imgPath = ROOT_PATH.'data/image_c/'.$pic;
        $data = array('media'=>'@'.$imgPath);
        $info = http_request_curl($upFileUrl,$data);
        if($info['media_id']){
            return $info['media_id'];
        }else{
            die(json_encode('图片素材上传失败'));
        }
    }

    //curl返回数组
    function http_request_curl($url, $data = null){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $output = curl_exec($curl);
        curl_close($curl);
        return json_decode($output,ture);
    }